package com.example.socket.core;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 连接SESSION上下文
 * @author Ramon
 */
public class SessionContext {

	/**
	 * SESSION 的身份标识
	 */
	private Object identity;

	/**
	 * SESSION KEY
	 */
	private String sessionId;

	/**
	 * SESSION上下文内容
	 */
	private Map<String, Object> content = new HashMap<>();

	// ----

	public SessionContext(String sessionId) {
		this.sessionId = sessionId;
	}

	// ---

	public synchronized Object putIfAbsent(String key, Object value) {
		Object absent = content.get(key);
		if (absent != null) {
			return absent;
		}
		return content.put(key, value);
	}

	public synchronized boolean remove(Object key, Object value) {
		Object absent = content.get(key);
		if (absent == null) {
			return false;
		}
		if (!absent.equals(value)) {
			return false;
		}
		content.remove(key);
		return true;
	}

	public synchronized boolean replace(String key, Object oldValue, Object newValue) {
		Object absent = content.get(key);
		if (absent != null) {
			if (oldValue.equals(absent)) {
				content.put(key, newValue);
				return true;
			}
		}
		return false;
	}

	public synchronized int size() {
		return content.size();
	}

	public synchronized boolean isEmpty() {
		return content.isEmpty();
	}

	public synchronized boolean containsKey(Object key) {
		return content.containsKey(key);
	}

	public synchronized boolean containsValue(Object value) {
		return content.containsValue(value);
	}

	public synchronized Object get(Object key) {
		return content.get(key);
	}

	public synchronized Object put(String key, Object value) {
		return content.put(key, value);
	}

	public synchronized Object remove(Object key) {
		return content.remove(key);
	}

	public synchronized void putAll(Map<? extends String, ? extends Object> m) {
		content.putAll(m);
	}

	public synchronized void clear() {
		content.clear();
	}

	public Set<String> keySet() {
		return new HashSet<>(content.keySet());
	}

	// --------

	public Object getIdentity() {
		return identity;
	}

	public synchronized void setIdentity(Object identity) {
		if (this.identity == null) {
			this.identity = identity;
		}
	}

	public String getSessionId() {
		return sessionId;
	}

}
